package net.arogarth.aws.android.manager.views;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import net.arogarth.aws.android.lib.AmazonElb;
import net.arogarth.aws.android.lib.AwsRequestException;
import net.arogarth.aws.android.lib.models.ElbInsance;
import net.arogarth.aws.android.lib.models.ElbInsanceState;
import net.arogarth.aws.android.manager.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class ElbList extends Activity {
	public class ElbListAdapter extends BaseAdapter implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

		private final List<ElbInsance> volumes = new ArrayList<ElbInsance>();
		private final Map<String, List<ElbInsanceState>> elbInstanceStates = new HashMap<String, List<ElbInsanceState>>();
		
		private Context context;

		public ElbListAdapter(Context view, ListView list) {
			this.context = view;

			list.setAdapter(this);
			list.setOnItemLongClickListener(this);
			this.loadData();
		}

		private void loadData() {
			final ProgressDialog pd = ProgressDialog.show(this.context,
					"Please Wait...", "Loading Data...", true, false);

			final Thread t = new Thread() {
				public void run() {
					AmazonElb aec2 = new AmazonElb();

					try {
						List<ElbInsance> _instances = aec2.describeLoadBalancers();

						volumes.clear();
						for (ElbInsance instance : _instances) {
							volumes.add(instance);
							
							List<ElbInsanceState> _states = aec2.describeInstanceHealth(instance.getLoadBalancerName());
							elbInstanceStates.put(instance.getLoadBalancerName(), _states);
						}

						
						handler.sendEmptyMessage(0);
					} catch (final AwsRequestException e) {
//						runOnUiThread(new Runnable() {
//							public void run() {
//								Toast.makeText(_context, e.getMessage(), Toast.LENGTH_SHORT).show();
//								finish();
//							}
//						});
					}
				}

				private Handler handler = new Handler() {
					@Override
					public void handleMessage(Message msg) {
						notifyDataSetChanged();
						pd.dismiss();
					}
				};
			};
			t.start();
		}

		public int getCount() {
			return this.volumes.size();
		}

		public ElbInsance getItem(int arg0) {
			return (ElbInsance) this.volumes.get(arg0);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final ElbInsance instance = (ElbInsance) getItem(position);

			final LinearLayout _ll = (LinearLayout) LayoutInflater.from(
					this.context).inflate(R.layout.elb_list_item, parent,
					false);

			((TextView) _ll.findViewById(R.id.elbName)).setText(instance.getLoadBalancerName());

			Integer active = 0;
			Integer total = 0;
			List<ElbInsanceState> states = this.elbInstanceStates.get(instance.getLoadBalancerName());
			total = states.size();
			for(ElbInsanceState state : states)
				if(state.getState().equalsIgnoreCase("InService")) active++;
			
			((TextView) _ll.findViewById(R.id.tvState)).setText(
					String.format("%s of %s nstances in Service", 
					active.toString(), total));
			
			((TextView) _ll.findViewById(R.id.tvDnsName)).setText(instance.getDnsName());//.replace(".", ". "));
			((TextView) _ll.findViewById(R.id.tvCheckInterval)).setText(instance.getHealthCheckInterval());
			((TextView) _ll.findViewById(R.id.tvCreated)).setText(instance.getCreatedTime());
			
			StringBuilder sb = new StringBuilder();
			
			for(ElbInsance.ElbPortConfiguration portConfig : instance.getPortCongiguration()) {
				if(sb.length() > 0) sb.append("\n");
				sb.append(String.format("%s to %s (%s)", portConfig.getElbPort(), portConfig.getInstancePort(), portConfig.getProtocol()));
			}
			((TextView) _ll.findViewById(R.id.tvPortconfig)).setText(sb.toString());
			
			return _ll;
		}
		
		

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, final View arg1, final int arg2, long arg3) {
			final ElbInsance elbInstance = this.getItem(arg2);
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
			
			String[] options = { "Add Instance", "Remove Instance", "View Instances" };
			
			builder.setItems(options,
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, final int which) {
					switch (which) {
					case 0: // Add Instance
						showPopupRegisterNewInstaces(arg2);
						break;
					case 1: // Remove Instance
						showPopupDeregisterdInstaces(arg2);
						break;
					case 2: // View Instances
						Bundle b = new Bundle();
						
						String[] strArray = new String[elbInstance.getInstances().size()];
						for(int i=0; i < elbInstance.getInstances().size(); i++)
							strArray[i] = elbInstance.getInstances().get(i);
						
						b.putStringArray("instances", strArray);
						Intent i = new Intent(arg1.getContext(), Ec2InstanceList.class);
						i.putExtras(b);
						
						startActivity(i);
						break;
					}
				}
			});
			
			builder.show();
			return true;
		}
		
		private void showPopupRegisterNewInstaces(int position) {
			ElbInsance instance = this.getItem(position);
			
			String[] strInstaceIds = new String[instance.getInstances().size()];
			for(int i=0; i< instance.getInstances().size(); i++)
				strInstaceIds[i] = instance.getInstances().get(i);
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
			
			builder.setItems(strInstaceIds, null);
			builder.show();
			
//			new AmazonElb().deregisterInstancesFromLoadBalancer(instance.getLoadBalancerName(), strInstaceIds);
		}
		
		private void showPopupDeregisterdInstaces(int position) {
			final ElbInsance instance = this.getItem(position);
			
			final String[] strInstaceIds = new String[instance.getInstances().size()];
			final boolean[] boolSelectedInstaceIds = new boolean[instance.getInstances().size()];
			
			for(int i=0; i< instance.getInstances().size(); i++) {
				strInstaceIds[i] = instance.getInstances().get(i);
				boolSelectedInstaceIds[i] = false;
			}
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
			builder.setTitle("Select Instances to Remove");
			
			builder.setMultiChoiceItems(strInstaceIds, null, new DialogInterface.OnMultiChoiceClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which, boolean isChecked) {
					boolSelectedInstaceIds[which] = isChecked;
				}
			});
			builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					List<String> strInstances = new ArrayList<String>();
					
					for(int i=0; i < boolSelectedInstaceIds.length; i++)
						if(boolSelectedInstaceIds[i]) strInstances.add(strInstaceIds[i]);
					
					new AmazonElb().deregisterInstancesFromLoadBalancer(instance.getLoadBalancerName(), strInstances.toArray(new String[0]));
				}
			});
			builder.show();
			
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.basic_list);
		final ListView lv = (ListView) findViewById(R.id.contentlist);
		new ElbListAdapter(ElbList.this, lv);
	}
}
